package org.itboys.pay.alipay;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.utils.string.CommonStringUtils;
import org.itboys.pay.constant.PayConstants;

import com.google.common.collect.Maps;

/**
 * 支付宝即时到账相关调用(PC支付)
 * 
 * @author huml
 */
public class AlipayDirectUtils {

	/**
	 * PC网页支付需要做的处理   返回表单字符串(页面H5代码)  redirect后进入阿里支付页面
	 * @param orderNo  订单编号
	 * @param subject  描述
	 * @param buyerEmail  卖家商户号
	 * @param totalFee  支付金额
	 * @return
	 */
	public static String getRedirectAlipayUrl(String orderNo, String subject,
			String buyerEmail, BigDecimal totalFee, String partner, String returnUrl, String notifyUrl, String privateKey) {
		AlipayDirectParam alipayDirectParam = AlipayDirectParam
				.getAlipayDirectParam(orderNo, subject, buyerEmail, totalFee);
		// 直接获取表单字符串
		String redirectAlipayUrl = AlipayDirectUtils
				.getRedirectAlipayUrl(alipayDirectParam, partner, buyerEmail, returnUrl, notifyUrl, privateKey);
		return redirectAlipayUrl;
	}

	/**
	 * 直接获得get请求支付宝支付页面的URL
	 * 
	 * @param alipayDirectParam
	 * @return
	 */
	private static String getRedirectAlipayUrl(
			AlipayDirectParam alipayDirectParam, String partner, String sellerEmail, String returnUrl, String notifyUrl, String privateKey) {
		Map<String, String> paramMap = AlipayDirectUtils
				.getAlipayUrlRequestParam(alipayDirectParam, partner, sellerEmail, returnUrl, notifyUrl, privateKey);
		StringBuilder redirectUrl = new StringBuilder();
		Set<Entry<String, String>> entrySet = paramMap.entrySet();
		for (Entry<String, String> entry : entrySet) {
			try {
				String value = StringUtils.isBlank(entry.getValue()) ? entry
						.getValue() : URLEncoder.encode(entry.getValue(),
						PayConstants.AliPay.DEFAULT_CHARSET);
				redirectUrl.append("&").append(entry.getKey()).append("=")
						.append(value);
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}

		}
		return PayConstants.AliPay.ALIPAY_GATEWAY_NEW + "?"
				+ redirectUrl.toString().substring(1);

	}

	/**
	 * 将支付宝请求参数 拼装成 form表单自动提交字符串
	 * 
	 * @param alipayDirectParam
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String getSubmitAlipayFormString(
			AlipayDirectParam alipayDirectParam, String partner, String sellerEmail, String returnUrl, String notifyUrl, String priateKey) {
		Map<String, String> paramMap = AlipayDirectUtils
				.getAlipayUrlRequestParam(alipayDirectParam, partner, sellerEmail, returnUrl, notifyUrl, priateKey);
		StringBuilder formStr = new StringBuilder();
		formStr.append("<form id='alipaysubmit' action='")
				.append(PayConstants.AliPay.ALIPAY_GATEWAY_NEW)/*
																 * .append(
																 * "_input_charset="
																 * ).append(
																 * AlipayConstants
																 * .
																 * DEFAULT_CHARSET
																 * )
																 */
				.append("' method='get' >");
		Set<Entry<String, String>> entrySet = paramMap.entrySet();
		for (Entry<String, String> entry : entrySet) {
			formStr.append("<input type='hidden' name='" + entry.getKey()
					+ "' value='" + entry.getValue() + "'/>");
		}
		formStr.append("</form>");
		formStr.append("<script>document.getElementById('alipaysubmit').submit();</script>");
		return formStr.toString();
	}

	/**
	 * 获取支付宝请求页面的接口map
	 * 
	 * @return
	 */
	private static Map<String, String> getAlipayUrlRequestParam(
			AlipayDirectParam alipayDirectParam, String partner, String sellerEmail, String returnUrl, String notifyUrl, String privateKey) {
		Map<String, String> paramMap = Maps.newHashMap();
		paramMap.put("service", PayConstants.AliPay.SERVICE_DIRECT); // 即时到账接口名称
		paramMap.put("payment_type", alipayDirectParam.getPaymentType()); // 支付类型
																			// 1商品购买
		paramMap.put("partner", partner); // 合作伙伴在支付宝的用户id
		paramMap.put("seller_email", sellerEmail);// 卖家email
		paramMap.put("return_url", returnUrl); // 同步返回的url
		paramMap.put("notify_url", notifyUrl); // 异步通知的url
		paramMap.put("out_trade_no", alipayDirectParam.getOrderId());
		paramMap.put("subject", alipayDirectParam.getSubject());
		paramMap.put("total_fee", CommonStringUtils.formatNumber(
				alipayDirectParam.getTotalFee().toString(), 2));
		paramMap.put("_input_charset", PayConstants.AliPay.DEFAULT_CHARSET);
		if (StringUtils.equals(alipayDirectParam.getPaymethod(),
				PayConstants.AliPay.PAY_METHOD_BANKPAY)) {
			paramMap.put("paymethod", alipayDirectParam.getPaymethod());
			paramMap.put("defaultbank", alipayDirectParam.getDefaultbank());
		}
		if (StringUtils.isNotBlank(alipayDirectParam.getToken())) {
			paramMap.put("token", alipayDirectParam.getToken());
		}
		// 签名结果与签名方式加入请求提交参数组中
		paramMap.put("sign", AlipayUtils.buildMysign(paramMap, privateKey));
		paramMap.put("sign_type", PayConstants.AliPay.SIGN_TYPE);
		return paramMap;
	}
}
